<?php
declare (strict_types=1);

namespace app\common\model;

use think\Model;
use think\response\Json;

class Menu extends Model
{
    protected $table = 'auth_rule';

    public function getMenu($map = '', $type = 1): array
    {
        try {
            if ($type == 1) {
                $map = empty($map) ? 'status = 1 and type = 1 and pid > 0 and is_del = 0' : 'status = 1 and id in(' . $map . ') and pid > 0 and type = 1 and is_del = 0';
            } else {
                $map = 'is_del = 0';
            }
            $result = $this->whereRaw($map)->order('sort', 'asc')->select()->toArray();

            return $type == 1 ? prepareMenu($result) : mergeMenu($result);
        } catch (\Exception $e) {

            return [];
        }
    }

    public function add($param): Json
    {
        try {
            if ($param['id']) {
                parent::update($param);
            } else {
                parent::create($param);
            }

        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function getAuth($id)
    {
        try {
            $result = $this->getMenu();
            $rule = Role::where('id', $id)->value('rules');
            if (!empty($rule)) {
                $rule = explode(',', $rule);
            }
            foreach ($result as &$vo) {
                $vo['checked'] = 0;
                if (!empty($rule) && in_array($vo['id'], $rule)) {
                    $vo['checked'] = 1;
                }
                foreach ($vo['child'] as &$co) {
                    $co['checked'] = 0;
                    if (!empty($rule) && in_array($co['id'], $rule)) {
                        $co['checked'] = 1;
                    }
                }

            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return $result;
    }

    public static function getNavigation($name): array
    {
        $s_nav = parent::where('name', $name)->field('pid,title')->find();
        $p_nav = '';
        if ($s_nav) {
            $p_nav = parent::where(['id' => $s_nav['pid']])->value('title');
        }

        return [
            's_nav' => $s_nav ? $s_nav['title'] : '未知',
            'p_nav' => $p_nav ?: '未知',
        ];
    }
}